namespace PHSRAG.Insight21.FormsManagement.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Collections;

	/// <summary>
	///	TextBoxItemEditor helps in creating a text box question.
	/// </summary>
	public partial class TextBoxItemEditor : System.Web.UI.UserControl
	{
		#region Constants
		private const string LoadedQuestionnaireItemKey = "LoadedQuestionnaireItemKey_F02CF1C2-562D-4924-BD20-059D52EC8109";
		private const string MultiLineListItemValue = "MultiLine";
		private const string DefaultRowsForMultiLineText = "3";
		private const string DefaultMaxChars = "4000";
		#endregion

		#region Instance Variables (private)
		private Policy.ICachePolicy pageCachePolicy;
		private Policy.ICachePolicy cachePolicy;
		private QuestionnaireItem textBoxQuestion;
		#endregion

		#region Instance Varibles (Protected)
		/// <summary>
		/// Sets the annunciator instance used to display any information to the user. This must be set by the control's container
		/// </summary>
		protected PHSRAG.WebControls.Annunciator annunciator;
		#endregion

		#region Properties
		/// <summary>
		/// Sets the annunciator instance used to display any information to the user. This must be set by the control's container
		/// </summary>
		public PHSRAG.WebControls.Annunciator Annunciator
		{
			set { annunciator = value; }
		}
		#endregion

		#region Events (Page)
		/// <summary>
		/// Populates data into corresponding controls.
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnPageLoad(object sender, System.EventArgs e)
		{
			if (annunciator == null)
				throw new Exception("Annunciator is not initialized.");

			annunciator.Message = string.Empty;
			if (!IsPostBack)
			{
				//bind the FormatOptions enum to the dropdown
				formatOptions.DataSource = Enum.GetNames(typeof(TextBoxQuestion.FormatOptions));
				formatOptions.DataBind();

				ItemEditor containerPage = (ItemEditor)Page;
				if (containerPage.SelectedQuestionnaireItemId != 0)
				{
					Hashtable questionnairesList = (Hashtable)cachePolicy.GetCachedObject(Keys.QuestionnaireObjectsKey);
					Questionnaire questionnaire = (Questionnaire)questionnairesList[containerPage.SelectedQuestionnaireID];
					QuestionnaireVersion questionnaireVersion = questionnaire.GetQuestionnaireVersionById( containerPage.SelectedQuestionnaireVersionID );
					textBoxQuestion = questionnaireVersion.GetQuestionnaireItemById( containerPage.SelectedQuestionnaireItemId );
					baseQuestionItemEditor.IsVersionDeployed = questionnaireVersion.IsDeployed;
					baseQuestionItemEditor.ItemName = textBoxQuestion.Name;
					baseQuestionItemEditor.ItemText = textBoxQuestion.Text;
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.TextModeProperty))
					{
						textMode.SelectedValue = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.TextModeProperty]).AttributeValue;
						if (textMode.SelectedValue == MultiLineListItemValue)
						{
							visibleRows.Enabled = true;
							visibleRowsRequiredValidator.Enabled = true;
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.RowsProperty))
							{
								visibleRows.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.RowsProperty]).AttributeValue;
							}
						}
						else
						{
							visibleRows.Enabled = false;
							visibleRows.Text = "1";
							visibleRowsRequiredValidator.Enabled = false;
						}
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.ColsProperty))
					{
						visibleCols.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ColsProperty]).AttributeValue;
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.ReadOnlyProperty))
					{
						readOnly.Checked = bool.Parse(((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ReadOnlyProperty]).AttributeValue);
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.FormatProperty))
					{
						TextBoxQuestion.FormatOptions formatOption = (TextBoxQuestion.FormatOptions)Enum.Parse(typeof(TextBoxQuestion.FormatOptions), ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.FormatProperty]).AttributeValue, true);
						formatOptions.SelectedValue = formatOption.ToString();
						SetFormatOptionsView(formatOption);
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxCharsProperty))
					{
						maxChars.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxCharsProperty]).AttributeValue;
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaskProperty))
					{
						numericMask.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaskProperty]).AttributeValue;
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MinValueProperty))
					{
						minValue.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MinValueProperty]).AttributeValue;
					}
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxValueProperty))
					{
						maxValue.Text = ((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxValueProperty]).AttributeValue;
					}
					baseQuestionItemEditor.Required = textBoxQuestion.Required;
					baseQuestionItemEditor.ValidationMessage = textBoxQuestion.ValidationMessage;
					baseQuestionItemEditor.HasSeparator = textBoxQuestion.HasSeparator;
				}
				else
				{
					textBoxQuestion = new QuestionnaireItem(cachePolicy);
					textBoxQuestion.Type = QuestionnaireItem.TextBoxItemType;
					textBoxQuestion.VersionId = containerPage.SelectedQuestionnaireVersionID;
					textBoxQuestion.Properties = new Hashtable();
					visibleRows.Text = "1";
					visibleRows.Enabled = false;
				}
				pageCachePolicy.Cache(LoadedQuestionnaireItemKey, textBoxQuestion);
			}
			else
			{
				textBoxQuestion = (QuestionnaireItem)pageCachePolicy.GetCachedObject(LoadedQuestionnaireItemKey);
			}

		}
		#endregion

		#region Web Form Designer generated code
		/// <summary>
		/// Page Initialization
		/// </summary>
		/// <param name="e">Arguments associated with the event.</param>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
			cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
		}

		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.OnPageLoad);

		}
		#endregion

		#region Private methods
		/// <summary>
		/// Displays an error message on the screen to the user with the exception, and all
		/// inner exception messages.
		/// </summary>
		/// <param name="ex">The exception to report on</param>
		private void DisplayExceptionReport(Exception ex)
		{
			annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
			annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
		}

		/// <summary>
		/// Based on the selected value for the format option, the corresponding view is displayed.
		/// </summary>
		private void SetFormatOptionsView(TextBoxQuestion.FormatOptions formatOption)
		{
			switch (formatOption)
			{
				case TextBoxQuestion.FormatOptions.None:
					formattingViews.ActiveViewIndex = -1;
					break;
				case TextBoxQuestion.FormatOptions.Alphabet:
				case TextBoxQuestion.FormatOptions.AlphaNumeric:
					formattingViews.ActiveViewIndex = 0;
					break;
				case TextBoxQuestion.FormatOptions.Numeric:
					formattingViews.ActiveViewIndex = 1;
					break;
			}
		}

		/// <summary>
		/// Deletes all the properties specific to the format option Numeric
		/// </summary>
		private void DeleteNumericProperties()
		{
			if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaskProperty))
				((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaskProperty]).MarkForDelete = true;
			if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MinValueProperty))
				((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MinValueProperty]).MarkForDelete = true;
			if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxValueProperty))
				((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxValueProperty]).MarkForDelete = true;
		}

		private void DeleteAlphaProperties()
		{
			if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxCharsProperty))
				((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxCharsProperty]).MarkForDelete = true;
		}
		#endregion

		#region Events (controls)
		/// <summary>
		/// Toggles the visible rows input control based on the textbox mode selected.
		/// Visible rows is only valid if the text box mode is set to multi-line.
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnTextModeSelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (textMode.SelectedValue == MultiLineListItemValue)
			{
				visibleRows.Enabled = true;
				visibleRows.Text = DefaultRowsForMultiLineText;
				visibleRowsRequiredValidator.Enabled = true;
			}
			else
			{
				visibleRows.Text = "1";
				visibleRows.Enabled = false;
				visibleRowsRequiredValidator.Enabled = false;
			}
		}

		/// <summary>
		/// Verifies that the question name is unique. If so,
		/// saves the questionnaire item and adds it to the versions collection (only if the item being created is a new one)
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnSaveItemClick(object sender, System.EventArgs e)
		{
			try
			{
				textBoxQuestion.Name = baseQuestionItemEditor.ItemName;

				ItemEditor containerPage = (ItemEditor)Page;
				Hashtable questionnairesList = (Hashtable)cachePolicy.GetCachedObject(Keys.QuestionnaireObjectsKey);
				Questionnaire questionnaire = (Questionnaire)questionnairesList[containerPage.SelectedQuestionnaireID];
				QuestionnaireVersion questionnaireVersion = (QuestionnaireVersion)questionnaire.GetQuestionnaireVersionById(containerPage.SelectedQuestionnaireVersionID);
				if (containerPage.SelectedQuestionnaireItemId == 0 && questionnaireVersion.DoesItemNameExists(textBoxQuestion.Name))
				{
					annunciator.Message = "Item name already exists. Please enter another name";
					return;
				}

				textBoxQuestion.Text = baseQuestionItemEditor.ItemText;
				if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.TextModeProperty))
					((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.TextModeProperty]).AttributeValue = textMode.SelectedValue;
				else
				{
					ItemProperty textModeProperty = new ItemProperty(cachePolicy);
					textModeProperty.AttributeName = TextBoxQuestion.PropertyNames.TextModeProperty;
					textModeProperty.AttributeValue = textMode.SelectedValue;
					textModeProperty.QuestionnaireItemId = textBoxQuestion.Id;
					textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.TextModeProperty] = textModeProperty;
				}
				if (textMode.SelectedValue != MultiLineListItemValue)
				{
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.RowsProperty))
					{
						ItemProperty rowsProperty = (ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.RowsProperty];
						rowsProperty.MarkForDelete = true;
					}
				}
				else
				{
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.RowsProperty))
					{
						((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.RowsProperty]).AttributeValue = visibleRows.Text;
					}
					else
					{
						ItemProperty rowsProperty = new ItemProperty(cachePolicy);
						rowsProperty.AttributeName = TextBoxQuestion.PropertyNames.RowsProperty;
						rowsProperty.AttributeValue = visibleRows.Text;
						rowsProperty.QuestionnaireItemId = textBoxQuestion.Id;
						textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.RowsProperty] = rowsProperty;
					}
				}
				if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.ColsProperty))
				{
					((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ColsProperty]).AttributeValue = visibleCols.Text;
				}
				else
				{
					ItemProperty colsProperty = new ItemProperty(cachePolicy);
					colsProperty.AttributeName = TextBoxQuestion.PropertyNames.ColsProperty;
					colsProperty.AttributeValue = visibleCols.Text;
					colsProperty.QuestionnaireItemId = textBoxQuestion.Id;
					textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ColsProperty] = colsProperty;
				}

				if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.ReadOnlyProperty))
				{
					if (!readOnly.Checked)
						((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ReadOnlyProperty]).MarkForDelete = true;
					else
						((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ReadOnlyProperty]).AttributeValue = readOnly.Checked.ToString();
				}
				else
				{
					if (readOnly.Checked)
					{
						ItemProperty readOnlyProperty = new ItemProperty(cachePolicy);
						readOnlyProperty.AttributeName = TextBoxQuestion.PropertyNames.ReadOnlyProperty;
						readOnlyProperty.AttributeValue = readOnly.Checked.ToString();
						readOnlyProperty.QuestionnaireItemId = textBoxQuestion.Id;
						textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.ReadOnlyProperty] = readOnlyProperty;
					}
				}

				TextBoxQuestion.FormatOptions formatOption = (TextBoxQuestion.FormatOptions)Enum.Parse(typeof(TextBoxQuestion.FormatOptions), formatOptions.SelectedValue);
				if (formatOption == TextBoxQuestion.FormatOptions.None)
				{
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.FormatProperty))
						((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.FormatProperty]).MarkForDelete = true;
					DeleteAlphaProperties();
					DeleteNumericProperties();
				}
				else
				{
					if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.FormatProperty))
						((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.FormatProperty]).AttributeValue = Enum.GetName(typeof(TextBoxQuestion.FormatOptions), formatOption);
					else
					{
						ItemProperty formatOptionProperty = new ItemProperty(cachePolicy);
						formatOptionProperty.AttributeName = TextBoxQuestion.PropertyNames.FormatProperty;
						formatOptionProperty.AttributeValue = Enum.GetName(typeof(TextBoxQuestion.FormatOptions), formatOption);
						formatOptionProperty.QuestionnaireItemId = textBoxQuestion.Id;
						textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.FormatProperty] = formatOptionProperty;
					}

					if (formatOption == TextBoxQuestion.FormatOptions.Alphabet || formatOption == TextBoxQuestion.FormatOptions.AlphaNumeric)
					{
						DeleteNumericProperties();
						if (maxChars.Text == DefaultMaxChars)
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxCharsProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxCharsProperty]).MarkForDelete = true;
						}
						else
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxCharsProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxCharsProperty]).AttributeValue = maxChars.Text;
							else
							{
								ItemProperty maxCharsProperty = new ItemProperty(cachePolicy);
								maxCharsProperty.AttributeName = TextBoxQuestion.PropertyNames.MaxCharsProperty;
								maxCharsProperty.AttributeValue = maxChars.Text;
								maxCharsProperty.QuestionnaireItemId = textBoxQuestion.Id;
								textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxCharsProperty] = maxCharsProperty;
							}
						}
					}
					if (formatOption == TextBoxQuestion.FormatOptions.Numeric)
					{
						DeleteAlphaProperties();
						if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaskProperty))
							((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaskProperty]).AttributeValue = numericMask.Text;
						else
						{
							ItemProperty maskProperty = new ItemProperty(cachePolicy);
							maskProperty.AttributeName = TextBoxQuestion.PropertyNames.MaskProperty;
							maskProperty.AttributeValue = numericMask.Text;
							maskProperty.QuestionnaireItemId = textBoxQuestion.Id;
							textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaskProperty] = maskProperty;
						}

						if (minValue.Text == string.Empty)
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MinValueProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MinValueProperty]).MarkForDelete = true;
						}
						else
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MinValueProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MinValueProperty]).AttributeValue = minValue.Text;
							else
							{
								ItemProperty minValueProperty = new ItemProperty(cachePolicy);
								minValueProperty.AttributeName = TextBoxQuestion.PropertyNames.MinValueProperty;
								minValueProperty.AttributeValue = minValue.Text;
								minValueProperty.QuestionnaireItemId = textBoxQuestion.Id;
								textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MinValueProperty] = minValueProperty;
							}
						}

						if (maxValue.Text == string.Empty)
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxValueProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxValueProperty]).MarkForDelete = true;
						}
						else
						{
							if (textBoxQuestion.Properties.ContainsKey(TextBoxQuestion.PropertyNames.MaxValueProperty))
								((ItemProperty)textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxValueProperty]).AttributeValue = maxValue.Text;
							else
							{
								ItemProperty maxValueProperty = new ItemProperty(cachePolicy);
								maxValueProperty.AttributeName = TextBoxQuestion.PropertyNames.MaxValueProperty;
								maxValueProperty.AttributeValue = maxValue.Text;
								maxValueProperty.QuestionnaireItemId = textBoxQuestion.Id;
								textBoxQuestion.Properties[TextBoxQuestion.PropertyNames.MaxValueProperty] = maxValueProperty;
							}
						}
					}
				}

				textBoxQuestion.Required = baseQuestionItemEditor.Required;
				textBoxQuestion.ValidationMessage = (textBoxQuestion.Required) ? baseQuestionItemEditor.ValidationMessage : string.Empty;
				textBoxQuestion.HasSeparator = baseQuestionItemEditor.HasSeparator;
				if (containerPage.SelectedQuestionnaireItemId == 0)
				{
					textBoxQuestion.Order = questionnaireVersion.GetMaxItemOrder() + 1;
				}

				textBoxQuestion.Save(Utility.DataAccess.ConnectionString);

				questionnaireVersion.Items = null;

				Response.Redirect(Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormEditorURL", "FormEditor.aspx"), false);
			}
			catch (Exception ex)
			{
				DisplayExceptionReport(ex);
			}

		}

		/// <summary>
		/// Redirects the user to the FormEditor page
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnCancelItemClick(object sender, System.EventArgs e)
		{
			Response.Redirect(Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormEditorURL", "FormEditor.aspx"));
		}

		/// <summary>
		/// Event fired when the Format Options dropdown is modified.
		/// 
		/// Based on the selected format, the corresponding detail view is made visible.
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnFormatOptionsSelectedIndexChanged(object sender, EventArgs e)
		{
			SetFormatOptionsView((TextBoxQuestion.FormatOptions)Enum.Parse(typeof(TextBoxQuestion.FormatOptions), formatOptions.SelectedValue));
		}
		#endregion
	}
}
